﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Models;
namespace Web
{
    public partial class counter : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int id = 0;
            if(Request.Form["cid"]!=null){
                try
                {
                    id = Int32.Parse(Request.Form["cid"].ToString());
                    if (CheckAndSetUserCookie(id, "cid")) {
                        NewsInfoLogic.NewsInfoCountAdd(id);
                        Response.Write("cid:" + id);
                    }
                    return;
                }
                catch
                {
                    return;
                }
            }else if(Request.Form["wid"]!=null){
                try
                {
                    id = Int32.Parse(Request.Form["wid"].ToString());
                    if (CheckAndSetUserCookie(id, "wid")) {
                        WorksInfoLogic.CountAddWorkInfo(id);
                        Response.Write("wid:" + id);
                    }
                    return;
                }
                catch
                {
                    return;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type">cid=>news sid=>works</param>
        /// <returns></returns>
        private bool CheckAndSetUserCookie(int id,string type)
        {
            HttpCookie cookie = Request.Cookies[type];
            bool got = false;
            string cookievalue = "";
            if (cookie != null)
            {
                string[] ids = cookie.Value.Split(',');
                foreach (var item in ids)
                {
                    if (item == id.ToString())
                    {
                        got = true;
                        break;
                    }
                }
                //用户在规定的时间段内已经点击过此新闻
                if (got)
                {
                    return false;
                }
                cookievalue = cookie.Value;
            }
            //用户没有cookie，或者有cookie但是没有点击过此条目，所以加cookie
            cookie = new HttpCookie(type);
            cookie.Value = cookievalue + "," + id.ToString();
            DateTime tommorow = DateTime.Now.Date.AddDays(1);
            cookie.Expires = tommorow;
            Response.Cookies.Add(cookie);
            return true;
        }
    }
}
